<template>
  <view class="plan-detail-container">
    <!-- 顶部导航栏 -->
    <cu-custom bgColor="bg-gradual-blue" :isBack="true">
      <block slot="content">计划详情</block>
      <block slot="right">
        <view class="flex align-center">
          <text class="cuIcon-edit text-white margin-right-sm" @tap="editPlan" v-if="planDetail.status === 'DRAFT'"></text>
          <text class="cuIcon-more text-white" @tap="showActionSheet = true"></text>
        </view>
      </block>
    </cu-custom>

    <scroll-view scroll-y class="detail-content" v-if="planDetail.id">
      <!-- 计划基本信息 -->
      <view class="info-card bg-white margin radius padding">
        <view class="card-header flex justify-between align-center margin-bottom">
          <text class="text-lg text-bold">{{ planDetail.planName }}</text>
          <view class="cu-tag" :class="planDetail.statusClass">
            {{ planDetail.statusText }}
          </view>
        </view>
        
        <view class="info-grid">
          <view class="info-item">
            <text class="label">订单编号</text>
            <text class="value">{{ planDetail.orderNo }}</text>
          </view>
          <view class="info-item">
            <text class="label">计划数量</text>
            <text class="value">{{ planDetail.planQuantity }}</text>
          </view>
          <view class="info-item">
            <text class="label">创建时间</text>
            <text class="value">{{ formatDateTime(planDetail.createTime) }}</text>
          </view>
          <view class="info-item">
            <text class="label">计划开始</text>
            <text class="value">{{ formatDateTime(planDetail.planStartTime) }}</text>
          </view>
          <view class="info-item">
            <text class="label">计划结束</text>
            <text class="value">{{ formatDateTime(planDetail.planEndTime) }}</text>
          </view>
          <view class="info-item">
            <text class="label">负责人</text>
            <text class="value">{{ planDetail.responsiblePerson }}</text>
          </view>
        </view>
      </view>

      <!-- 进度概览 -->
      <view class="progress-card bg-white margin radius padding">
        <view class="card-header flex justify-between align-center margin-bottom">
          <text class="text-lg text-bold">生产进度</text>
          <text class="text-sm" :class="planDetail.progressColorClass">
            {{ planDetail.progress }}%
          </text>
        </view>
        
        <view class="progress-bar margin-bottom">
          <view 
            class="progress-fill" 
            :class="planDetail.progressColorClass"
            :style="{ width: planDetail.progress + '%' }"
          ></view>
        </view>
        
        <view class="progress-stats flex justify-between">
          <view class="stat-item text-center">
            <text class="text-xl text-bold text-blue">{{ planDetail.totalTasks || 0 }}</text>
            <text class="text-xs text-gray">总任务</text>
          </view>
          <view class="stat-item text-center">
            <text class="text-xl text-bold text-orange">{{ planDetail.pendingTasks || 0 }}</text>
            <text class="text-xs text-gray">待处理</text>
          </view>
          <view class="stat-item text-center">
            <text class="text-xl text-bold text-green">{{ planDetail.completedTasks || 0 }}</text>
            <text class="text-xs text-gray">已完成</text>
          </view>
          <view class="stat-item text-center">
            <text class="text-xl text-bold text-red">{{ planDetail.delayedTasks || 0 }}</text>
            <text class="text-xs text-gray">延期</text>
          </view>
        </view>
      </view>

      <!-- 任务列表 -->
      <view class="task-card bg-white margin radius padding">
        <view class="card-header flex justify-between align-center margin-bottom">
          <text class="text-lg text-bold">任务列表</text>
          <text class="text-blue text-sm" @tap="goToTaskList">查看全部</text>
        </view>
        
        <view v-if="taskList.length > 0">
          <view 
            v-for="(task, index) in taskList" 
            :key="task.id"
            class="task-item padding-sm"
            :class="{ 'border-bottom': index < taskList.length - 1 }"
            @tap="goToTaskDetail(task.id)"
          >
            <view class="flex justify-between align-center margin-bottom-xs">
              <text class="text-bold">{{ task.taskName }}</text>
              <view class="cu-tag sm" :class="task.statusClass">
                {{ task.statusText }}
              </view>
            </view>
            
            <view class="flex justify-between align-center">
              <view class="flex align-center">
                <text class="cuIcon-profile text-blue margin-right-xs"></text>
                <text class="text-sm text-gray">{{ task.workTypeName }}</text>
              </view>
              <text class="text-sm text-gray">{{ task.assigneeName || '未分配' }}</text>
            </view>
            
            <view class="task-progress margin-top-xs">
              <view class="flex justify-between align-center margin-bottom-xs">
                <text class="text-xs text-gray">进度</text>
                <text class="text-xs" :class="task.progressColorClass">
                  {{ task.progress }}%
                </text>
              </view>
              <view class="mini-progress-bar">
                <view 
                  class="mini-progress-fill" 
                  :class="task.progressColorClass"
                  :style="{ width: task.progress + '%' }"
                ></view>
              </view>
            </view>
          </view>
        </view>
        
        <view v-else class="empty-tasks text-center padding">
          <text class="text-gray">暂无任务</text>
        </view>
      </view>

      <!-- 操作记录 -->
      <view class="log-card bg-white margin radius padding">
        <view class="card-header margin-bottom">
          <text class="text-lg text-bold">操作记录</text>
        </view>
        
        <view v-if="logList.length > 0">
          <view 
            v-for="(log, index) in logList" 
            :key="index"
            class="log-item padding-sm"
            :class="{ 'border-bottom': index < logList.length - 1 }"
          >
            <view class="flex justify-between align-center">
              <view>
                <text class="text-bold">{{ log.operation }}</text>
                <text class="text-sm text-gray margin-left-sm">{{ log.operator }}</text>
              </view>
              <text class="text-xs text-gray">{{ formatDateTime(log.createTime) }}</text>
            </view>
            <text class="text-sm text-gray margin-top-xs" v-if="log.remark">{{ log.remark }}</text>
          </view>
        </view>
        
        <view v-else class="empty-logs text-center padding">
          <text class="text-gray">暂无记录</text>
        </view>
      </view>
    </scroll-view>

    <!-- 加载状态 -->
    <view v-else class="loading-state text-center padding-xl">
      <text class="cuIcon-loading2 cuIconfont-spin text-blue text-xl"></text>
      <text class="text-gray margin-top">加载中...</text>
    </view>

    <!-- 操作菜单 -->
    <view v-if="showActionSheet" class="cu-modal bottom-modal show" @tap="showActionSheet = false">
      <view class="cu-dialog" @tap.stop="">
        <view class="cu-bar bg-white">
          <view class="action">
            <text class="text-blue" @tap="showActionSheet = false">取消</text>
          </view>
        </view>
        <view class="grid col-1 padding-sm">
          <view 
            v-if="planDetail.status === 'DRAFT'"
            class="padding-xl text-center"
            @tap="startPlan"
          >
            <text class="cuIcon-play text-blue text-xl"></text>
            <text class="margin-left-sm">启动计划</text>
          </view>
          <view 
            v-if="planDetail.status === 'IN_PROGRESS'"
            class="padding-xl text-center"
            @tap="pausePlan"
          >
            <text class="cuIcon-pause text-orange text-xl"></text>
            <text class="margin-left-sm">暂停计划</text>
          </view>
          <view 
            v-if="planDetail.status === 'PAUSED'"
            class="padding-xl text-center"
            @tap="resumePlan"
          >
            <text class="cuIcon-play text-green text-xl"></text>
            <text class="margin-left-sm">恢复计划</text>
          </view>
          <view 
            v-if="['IN_PROGRESS', 'PAUSED'].includes(planDetail.status)"
            class="padding-xl text-center"
            @tap="completePlan"
          >
            <text class="cuIcon-check text-green text-xl"></text>
            <text class="margin-left-sm">完成计划</text>
          </view>
          <view class="padding-xl text-center" @tap="refreshData">
            <text class="cuIcon-refresh text-blue text-xl"></text>
            <text class="margin-left-sm">刷新数据</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { productionPlan, productionTask } from '@/api/mes/productionPlanV2.js'

export default {
  data() {
    return {
      planId: '',
      planDetail: {},
      taskList: [],
      logList: [],
      loading: false,
      showActionSheet: false
    }
  },
  
  onLoad(options) {
    this.planId = options.id
    if (this.planId) {
      this.loadPlanDetail()
      this.loadTaskList()
      this.loadOperationLog()
    }
  },
  
  onShow() {
    // 页面显示时刷新数据
    if (this.planId) {
      this.refreshData()
    }
  },
  
  methods: {
    // 加载计划详情
    async loadPlanDetail() {
      try {
        const response = await productionPlan.getDetail(this.planId)
        this.planDetail = this.processPlanData(response)
      } catch (error) {
        console.error('加载计划详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    },
    
    // 加载任务列表
    async loadTaskList() {
      try {
        const response = await productionTask.getList({
          planId: this.planId,
          current: 1,
          size: 5
        })
        
        this.taskList = (response.records || []).map(item => ({
          ...item,
          statusClass: this.calculateTaskStatusClass(item.status),
          statusText: this.calculateTaskStatusText(item.status),
          progressColorClass: this.calculateProgressColorClass(item.progress)
        }))
      } catch (error) {
        console.error('加载任务列表失败:', error)
      }
    },
    
    // 加载操作记录
    async loadOperationLog() {
      try {
        // 这里应该调用实际的操作记录接口
        // const response = await productionPlan.getOperationLog(this.planId)
        // 暂时使用模拟数据
        this.logList = [
          {
            operation: '创建计划',
            operator: '张三',
            createTime: new Date().toISOString(),
            remark: '初始创建生产计划'
          }
        ]
      } catch (error) {
        console.error('加载操作记录失败:', error)
      }
    },
    
    // 刷新数据
    refreshData() {
      this.loadPlanDetail()
      this.loadTaskList()
      this.loadOperationLog()
    },
    
    // 计算状态样式类
    calculateStatusClass(status) {
      const statusMap = {
        'DRAFT': 'bg-gray',
        'IN_PROGRESS': 'bg-blue',
        'PAUSED': 'bg-orange',
        'COMPLETED': 'bg-green'
      }
      return statusMap[status] || 'bg-gray'
    },
    
    // 计算状态文本
    calculateStatusText(status) {
      const statusMap = {
        'DRAFT': '草稿',
        'IN_PROGRESS': '进行中',
        'PAUSED': '已暂停',
        'COMPLETED': '已完成'
      }
      return statusMap[status] || '未知'
    },
    
    // 计算任务状态样式类
    calculateTaskStatusClass(status) {
      const statusMap = {
        'PENDING': 'bg-gray',
        'CLAIMED': 'bg-orange',
        'IN_PROGRESS': 'bg-blue',
        'PAUSED': 'bg-orange',
        'COMPLETED': 'bg-green'
      }
      return statusMap[status] || 'bg-gray'
    },
    
    // 计算任务状态文本
    calculateTaskStatusText(status) {
      const statusMap = {
        'PENDING': '待领取',
        'CLAIMED': '已领取',
        'IN_PROGRESS': '进行中',
        'PAUSED': '已暂停',
        'COMPLETED': '已完成'
      }
      return statusMap[status] || '未知'
    },
    
    // 计算进度颜色类（用于数据预处理）
    calculateProgressColorClass(progress) {
      if (progress >= 100) return 'text-green'
      if (progress >= 80) return 'text-blue'
      if (progress >= 50) return 'text-orange'
      return 'text-red'
    },
    
    // 格式化日期时间
    formatDateTime(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    },
    
    // 启动计划
    async startPlan() {
      this.showActionSheet = false
      try {
        await productionPlan.start(this.planId)
        uni.showToast({
          title: '启动成功',
          icon: 'success'
        })
        this.refreshData()
      } catch (error) {
        console.error('启动计划失败:', error)
        uni.showToast({
          title: '启动失败',
          icon: 'none'
        })
      }
    },
    
    // 暂停计划
    async pausePlan() {
      this.showActionSheet = false
      try {
        await productionPlan.pause(this.planId)
        uni.showToast({
          title: '暂停成功',
          icon: 'success'
        })
        this.refreshData()
      } catch (error) {
        console.error('暂停计划失败:', error)
        uni.showToast({
          title: '暂停失败',
          icon: 'none'
        })
      }
    },
    
    // 恢复计划
    async resumePlan() {
      this.showActionSheet = false
      try {
        await productionPlan.start(this.planId)
        uni.showToast({
          title: '恢复成功',
          icon: 'success'
        })
        this.refreshData()
      } catch (error) {
        console.error('恢复计划失败:', error)
        uni.showToast({
          title: '恢复失败',
          icon: 'none'
        })
      }
    },
    
    // 完成计划
    async completePlan() {
      this.showActionSheet = false
      uni.showModal({
        title: '确认完成',
        content: '确定要完成这个生产计划吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              await productionPlan.complete(this.planId)
              uni.showToast({
                title: '完成成功',
                icon: 'success'
              })
              this.refreshData()
            } catch (error) {
              console.error('完成计划失败:', error)
              uni.showToast({
                title: '完成失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    // 编辑计划
    editPlan() {
      uni.navigateTo({
        url: `/pages/production/plan/create?id=${this.planId}&type=edit`
      })
    },
    
    // 跳转到任务列表
    goToTaskList() {
      uni.navigateTo({
        url: `/pages/production/task/list?planId=${this.planId}`
      })
    },
    
    // 跳转到任务详情
    goToTaskDetail(taskId) {
      uni.navigateTo({
        url: `/pages/production/task/detail?id=${taskId}`
      })
    }
  }
}
</script>

<style scoped>
.plan-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.detail-content {
  height: calc(100vh - 100rpx);
}

.card-header {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 20rpx;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
}

.info-item {
  display: flex;
  flex-direction: column;
}

.info-item .label {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 8rpx;
}

.info-item .value {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.progress-bar {
  height: 12rpx;
  background-color: #f0f0f0;
  border-radius: 6rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  border-radius: 6rpx;
  transition: width 0.3s ease;
}

.progress-fill.text-green {
  background-color: #34c759;
}

.progress-fill.text-blue {
  background-color: #007aff;
}

.progress-fill.text-orange {
  background-color: #ff9500;
}

.progress-fill.text-red {
  background-color: #ff3b30;
}

.progress-stats {
  margin-top: 20rpx;
}

.stat-item {
  flex: 1;
  text-align: center;
}

.stat-item text:first-child {
  display: block;
}

.stat-item text:last-child {
  display: block;
  margin-top: 8rpx;
}

.task-item {
  border-radius: 8rpx;
  background-color: #fafafa;
  margin-bottom: 16rpx;
}

.task-item:last-child {
  margin-bottom: 0;
}

.mini-progress-bar {
  height: 6rpx;
  background-color: #f0f0f0;
  border-radius: 3rpx;
  overflow: hidden;
}

.mini-progress-fill {
  height: 100%;
  border-radius: 3rpx;
  transition: width 0.3s ease;
}

.mini-progress-fill.text-green {
  background-color: #34c759;
}

.mini-progress-fill.text-blue {
  background-color: #007aff;
}

.mini-progress-fill.text-orange {
  background-color: #ff9500;
}

.mini-progress-fill.text-red {
  background-color: #ff3b30;
}

.log-item {
  border-radius: 8rpx;
  background-color: #fafafa;
  margin-bottom: 16rpx;
}

.log-item:last-child {
  margin-bottom: 0;
}

.loading-state {
  margin-top: 200rpx;
}

.empty-tasks,
.empty-logs {
  padding: 60rpx 0;
}

.bottom-modal .cu-dialog {
  border-radius: 20rpx 20rpx 0 0;
}
</style>
